/**
* 使用 P 标签包裹body子元素当中的内敛元素
*/
(function(E, $){

var Consts = E.consts,
	reBlock = /^(area|p|blockquote|center|dir|div|form|ol|ul|pre|dl|table|h[123456r]|audio|canvas|section|video)$/i,
	
Filter = E.addFilter('paragraph', {
	replace: function( dom ){
		if(typeof dom !='object' || !dom.body){return dom;}
		var node, childs = E.$("body")[0].childNodes,
			paragraphList = [], paragraph = [];
		
		for (var i = 0, len = childs.length; i < len; i++){
			node = childs[i];
			
			if (1 === node.nodeType){
				// 元素
				if( reBlock.test(node.nodeName) ){
					if( paragraph.length ){
						paragraphList.push( paragraph );
						paragraph = [];
					}
					// 去掉段落开头可能存在的空格
					// $(node).html( E.$(node).html().replace(/^(\s|&nbsp;|　)+/i, '') );
				}else{
					// 非段落元素
					paragraph.push(node);
				}
			}else if (3 === node.nodeType ){
				// 文本
				var text = $.trim( E.$(node).text() );
				if( text ){
					E.$(node).text(text);
					paragraph.push(node);
				}
			}else {
				// 其他一律丢弃
			}
		}
		
		if( paragraph.length ){
			paragraphList.push( paragraph );
		}
		
		for (var i = 0, len = paragraphList.length; i < len; i++){
			var p = dom.createElement('p'),
				sublist = paragraphList[i];
			
			E.$(sublist[0]).before(p);
			
			for (var j = 0, len2 = sublist.length; j < len2; j++){
				E.$(p).append( sublist[j] );
			}
		}
	}
});

// 在编辑器打开时即执行此过滤器
E.Event.bind('oncomplete', function(e){
	Filter.replace(e.dom);
});

})(jQEditor, jQuery);